const express = require("express");
const fs = require("fs");
const path = require("path");

function loadControllers() {
  const router = express.Router();
  let controllers = {};

  try {
    // 检查是否在 webpack 打包环境中
    // 注意：webpack 5 中需要正确配置 require.context
    if (typeof __webpack_require__ !== "undefined") {
      console.log("Running in webpack environment");

      // 方式1：使用 require.context（需要在 webpack 配置中启用）
      try {
        // 创建一个 context 来导入所有 Controller 文件
        const context = require.context("./", false, /Controller\.js$/);
        context.keys().forEach((key) => {
          // 跳过 index.js
          if (key === "./index.js") return;

          try {
            const controller = context(key);
            const fileName = path.basename(key, ".js");
            const prefix = fileName.replace("Controller", "");

            // 检查导出的格式
            const routePrefix = controller.routePrefix || prefix.toLowerCase();
            const routerInstance =
              controller.router || controller.default?.router || controller;

            if (routerInstance && typeof routerInstance.use === "function") {
              controllers[routePrefix] = controller;
              router.use(`/${routePrefix}`, routerInstance);
              console.log(
                `✓ Loaded controller: ${fileName} with prefix /${routePrefix}`
              );
            } else {
              console.error(`✗ Invalid controller format in ${fileName}`);
            }
          } catch (error) {
            console.error(`✗ Error loading controller ${key}:`, error.message);
          }
        });
      } catch (contextError) {
        console.error("require.context failed, falling back to manual imports");
        // 方式2：手动导入（更可靠的备选方案）
        loadControllersManually(router, controllers);
      }
    } else {
      // Node.js 环境：使用 fs.readdirSync
      console.log("Running in Node.js environment");
      const files = fs.readdirSync(__dirname);
      files.forEach((file) => {
        if (file !== "index.js" && file.endsWith("Controller.js")) {
          try {
            const filePath = path.join(__dirname, file);
            const controller = require(filePath);
            const prefix = path.basename(file, ".js").replace("Controller", "");
            const routePrefix = controller.routePrefix || prefix.toLowerCase();

            if (controller.router) {
              controllers[routePrefix] = controller;
              router.use(`/${routePrefix}`, controller.router);
              console.log(
                `✓ Loaded controller: ${file} with prefix /${routePrefix}`
              );
            } else {
              console.error(`✗ No router found in ${file}`);
            }
          } catch (error) {
            console.error(`✗ Error loading controller ${file}:`, error.message);
          }
        }
      });
    }

    // 输出加载结果统计
    const loadedCount = Object.keys(controllers).length;
    if (loadedCount > 0) {
      console.log(`\n📦 Successfully loaded ${loadedCount} controller(s):`);
      Object.keys(controllers).forEach((key) => {
        console.log(`   - /${key}`);
      });
    } else {
      console.warn("⚠️  No controllers were loaded!");
    }
  } catch (error) {
    console.error("Fatal error in loadControllers:", error);
    // 最后的备用方案：手动导入已知的控制器
    loadControllersManually(router, controllers);
  }

  return router;
}

// 手动导入控制器的备用方法
function loadControllersManually(router, controllers) {
  console.log("Using manual controller import method...");

  try {
    // 手动导入已知的控制器
    // 根据你的 loginController.js，添加其他控制器的导入
    const loginController = require("./loginController");

    // 注册 loginController
    if (loginController && loginController.router) {
      const routePrefix = loginController.routePrefix || "login";
      controllers[routePrefix] = loginController;
      router.use(`/${routePrefix}`, loginController.router);
      console.log(
        `✓ Manually loaded loginController with prefix /${routePrefix}`
      );
    }

    // 如果有其他控制器，在这里添加
    // const userController = require('./userController');
    // if (userController && userController.router) {
    //   const routePrefix = userController.routePrefix || 'user';
    //   controllers[routePrefix] = userController;
    //   router.use(`/${routePrefix}`, userController.router);
    //   console.log(`✓ Manually loaded userController with prefix /${routePrefix}`);
    // }
  } catch (error) {
    console.error("Manual controller loading failed:", error);
  }
}

// 导出时立即执行
const controllerRouter = loadControllers();

module.exports = controllerRouter;
